package StudyCode.summary.mycollection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CollectionsMethodSortWithACustomComparatorObject {
	public static void main(String[] args) {
		List<Time> list = new ArrayList<>(); // create List

		list.add(new Time(6, 24, 34));
		list.add(new Time(18, 14, 58));
		list.add(new Time(16, 15, 34));
		list.add(new Time(12, 14, 58));
		list.add(new Time(6, 24, 22));

		System.out.printf("排序前， array 元素:%n%s%n", list);

		Collections.sort(list, new TimeComparator());

		System.out.printf("排序后， array 元素:%n%s%n", list);
	}
}

class Time {
	private int hour; // 0 - 23
	private int minute; // 0 - 59
	private int second; // 0 - 59

	public Time(int h, int m, int s) {
		setTime(h, m, s);
	}


	public void setTime(int h, int m, int s) {
		setHour(h); // set the hour
		setMinute(m); // set the minute
		setSecond(s); // set the second
	}

	public void setHour(int h) {
		if (h >= 0 && h < 24)
			hour = h;
	}

	public void setMinute(int m) {
		if (m >= 0 && m < 60)
			minute = m;
		else
			throw new IllegalArgumentException("minute must be 0-59");
	}

	// validate and set second
	public void setSecond(int s) {
		if (s >= 0 && s < 60)
			second = ((s >= 0 && s < 60) ? s : 0);

	}

	public int getHour() {
		return hour;
	}

	public int getMinute() {
		return minute;
	}

	public int getSecond() {
		return second;
	}


	public String toString() {
		return String.format("%d:%02d:%02d %s",
				((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12),
				getMinute(), getSecond(), (getHour() < 12 ? "AM" : "PM"));
	}
}

class TimeComparator implements java.util.Comparator<Time> {
	@Override
	public int compare(Time time1, Time time2) {
		int hourDifference = time1.getHour() - time2.getHour();

		if (hourDifference != 0) // test the hour first
			return hourDifference;

		int minuteDifference = time1.getMinute() - time2.getMinute();

		if (minuteDifference != 0) // then test the minute
			return minuteDifference;

		int secondDifference = time1.getSecond() - time2.getSecond();
		return secondDifference;
	}
}
